package com.ecarx.module_vehicle;

import android.util.Log;
import android.view.View;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.ScrollView;
import android.widget.TextView;

import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.ecarx.library_base.base_fragment.BaseFragment;
import com.ecarx.module_vehicle.signal.Model.AreaId;
import com.ecarx.module_vehicle.signal.Model.InPropertyValue;
import com.ecarx.module_vehicle.signal.Model.Rate;
import com.ecarx.module_vehicle.signal.Model.SignalItem;
import com.ecarx.module_vehicle.signal.Model.UISelectPosition;
import com.ecarx.module_vehicle.signal.Model.WrappedPropertyId;
import com.ecarx.module_vehicle.signal.adatpter.BusinessAdapter;
import com.ecarx.module_vehicle.signal.adatpter.SignalAdapter;
import com.ecarx.module_vehicle.signal.controller.VsController;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

public class VehicleSignalFragment extends BaseFragment implements VsController.EventCallback {
    private RecyclerView mRvTopBusiness, mRvSignal;
    private BusinessAdapter mBusinessAdapter;
    private SignalAdapter mSignalAdapter;
    private final VsController mVsController = new VsController();
    private TextView mTvLog;
    private Map<String, List<SignalItem>> mSignalModel;
    private CheckBox mCbAll;
    private ScrollView mScLog;

    public VehicleSignalFragment() {
        // Required empty public constructor
    }

    @Override
    protected int layoutId() {
        return R.layout.fragment_vhicle_signal;
    }

    @Override
    protected void init(View view) {
        findView(view);
        initData();
    }

    private void findView(View view) {
        mRvTopBusiness = view.findViewById(R.id.rv_business);
        mRvSignal = view.findViewById(R.id.rv_detail);
        mCbAll = view.findViewById(R.id.cb_all);
        mTvLog = view.findViewById(R.id.tv_log);
        mScLog = view.findViewById(R.id.sc_log);
        TextView tvLogClean = view.findViewById(R.id.tv_logclean);
        mRvTopBusiness.setLayoutManager(new LinearLayoutManager(getActivity(), LinearLayoutManager.HORIZONTAL, false));
        mRvSignal.setLayoutManager(new LinearLayoutManager(getActivity()));
        tvLogClean.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                String moduleName = mSignalAdapter.getModuleName();
                mVsController.clearLogByModuleName(moduleName);
            }
        });
        mBusinessAdapter = new BusinessAdapter(new BusinessAdapter.onItemClickListener() {
            @Override
            public void onItemClick(View view, int postion, Object o) {
                refreshSignalView((String) o);
            }
        });
        mSignalAdapter = new SignalAdapter(getActivity(), new SignalAdapter.OnSignalAdapterCallback() {
            @Override
            public void onRegisterCallback(String moduleName, WrappedPropertyId wrappedPropertyId, Rate rate) {
                mVsController.registerCallback(moduleName, wrappedPropertyId, rate);
                checkSelectAll(moduleName);
            }

            @Override
            public void onUnRegisterCallback(String moduleName, WrappedPropertyId wrappedPropertyId) {
                mVsController.unRegisterCallback(moduleName, wrappedPropertyId);
                checkSelectAll(moduleName);
            }

            @Override
            public void onSetCallback(String moduleName, WrappedPropertyId wrappedPropertyId, AreaId areaId, InPropertyValue inPropertyValue) {
                mVsController.executeSet(moduleName, wrappedPropertyId, areaId, inPropertyValue);
            }

            @Override
            public void onGetCallback(String moduleName, WrappedPropertyId wrappedPropertyId, AreaId areaId) {
                mVsController.executeGet(moduleName, wrappedPropertyId, areaId);
            }
        });
        mRvTopBusiness.setAdapter(mBusinessAdapter);
        mRvSignal.setAdapter(mSignalAdapter);
    }

    private void initData() {
        mVsController.init(this);
        mSignalModel = mVsController.getSignalModel();
        ArrayList<String> topLists = new ArrayList<>(mSignalModel.keySet());
        Log.d(TAG, "init: " + mSignalModel);
        mBusinessAdapter.setList(topLists);
        if (!topLists.isEmpty()) {
            refreshSignalView(topLists.get(0));
        }
    }

    /**
     * 刷新所有界面
     */
    private void refreshSignalView(String moduleName) {
        List<SignalItem> datas = mSignalModel.get(moduleName);
        mSignalAdapter.setList(datas, moduleName);
        onLogChanged(moduleName, mVsController.getLogRecordMap().get(moduleName).toString());
        checkSelectAll(moduleName);
    }

    private void checkSelectAll(String moduleName) {
        List<SignalItem> signalItemList = mSignalModel.get(moduleName);
        boolean checked = signalItemList.stream().filter((signalItem) -> !signalItem.getUiSelectPosition().isRegistered()).count() > 0;
        mCbAll.setOnCheckedChangeListener(null);
        mCbAll.setChecked(!checked);
        mCbAll.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
                List<SignalItem> signalItemList = mSignalModel.get(mSignalAdapter.getModuleName());
                signalItemList.stream().filter((signalItem) -> signalItem.getUiSelectPosition().isRegistered() != isChecked)
                        .forEach(signalItem -> {
                            if (isChecked) {
                                Rate rate = signalItem.getRateList().get(signalItem.getUiSelectPosition().getRateSelectPosition());
                                mVsController.registerCallback(signalItem.getModuleName(), signalItem.getWrappedPropertyId(), rate);
                            } else {
                                mVsController.unRegisterCallback(signalItem.getModuleName(), signalItem.getWrappedPropertyId());
                            }
                            UISelectPosition uiSelectPosition = signalItem.getUiSelectPosition();
                            uiSelectPosition.setRegistered(isChecked);
                        });
                mSignalAdapter.notifyDataSetChanged();
            }
        });
    }

    @Override
    public void onLogChanged(String moduleName, String log) {
        if (!moduleName.equals(mSignalAdapter.getModuleName())) {
            return;
        }
        mTvLog.post(new Runnable() {
            @Override
            public void run() {
                mTvLog.setText(log);
                mScLog.fullScroll(View.FOCUS_DOWN);
            }
        });
    }
}